#include "OpfBuilder.h"
#include <string.h>

using namespace std;

OpfBuilder::OpfBuilder(void)
{
  m_content = new char[CONTENT_SIZE];
  memset((void*)m_content, 0x00, CONTENT_SIZE * sizeof(char));
}

OpfBuilder::~OpfBuilder(void)
{
  if(m_content != NULL)
  {
    delete[] m_content;
    m_content = NULL;
  }
}

void OpfBuilder::initialize()
{
  memset((void*)m_content, 0x00, CONTENT_SIZE * sizeof(char));
  memset((void*)&m_opfInfo, 0x00, sizeof(m_opfInfo));
}

void OpfBuilder::addMetadata(const articleInfo::ArticleInfo& article)
{
  sprintf(m_opfInfo.metadata, OPF_META_DATA,
    article.articlename.c_str(), article.author.c_str(),
    article.intro.c_str(), article.authorid.c_str(),
    article.sortid.c_str(), article.ctypeid.c_str(), article.articletype,
    article.permission, article.firstflag, article.fullflag,
    article.imgflag, article.power, article.display,
    article.lastupdate.c_str());
}

void OpfBuilder::addMainfestAndSpine(const chapterInfo::ChapterInfo& chapter)
{
  char tmp[OPF_SIZE] ={0};
  sprintf(tmp, OPF_ITEM, chapter.chaptername.c_str(), chapter.chapterid.c_str());
  strcat(m_opfInfo.mainfest, tmp);
  sprintf(tmp, OPF_ITEMREF, chapter.chaptername.c_str());
  strcat(m_opfInfo.spine, tmp);
}

bool OpfBuilder::confirmOptFile(const char* filePath, const long articleid)
{
  static char tmpPath[1024] = {0};
  //edit by san
  sprintf(tmpPath, "%s/files/article/txt/%ld/%ld", filePath, articleid / mover::SIZE_FILE_SPLIT_UNIT, articleid);
  if(!m_file.isExists(tmpPath))
  {
    m_file.checkDir(tmpPath);
  }
  strcat(tmpPath, "/index.opf");
  sprintf(m_content, OPF_PACKAGE, m_opfInfo.metadata, m_opfInfo.mainfest, m_opfInfo.spine);
  if(m_file.isExists(tmpPath))
  {
    m_file.deleteFile(tmpPath);
  }
  return m_file.writeFile(m_content, strlen(m_content), tmpPath);
}


